package com.sali.disruptor;

import com.lmax.disruptor.RingBuffer;
import com.sali.disruptor.entity.MessageEvent;
import lombok.Builder;
import lombok.Data;

/**
 * @description: 封装 disruptor 存放数据过程
 * @author: sali
 * @date: 2025/2/22 下午2:57.
 * @version: 1.0
 */
@Data
public class MessageProducer {
    private DisruptorComponent disruptorComponent;

    @Builder(builderMethodName = "createBuilder")
    public MessageProducer(DisruptorComponent disruptorComponent) {
        this.disruptorComponent = disruptorComponent;
    }

    /**
     * 添加数据
     *
     * @param message
     */
    public <T> void putData(T message) {
        RingBuffer<MessageEvent> ringBuffer = disruptorComponent.getDisruptor().getRingBuffer();
        long seq = ringBuffer.next();
        try {
            MessageEvent data = ringBuffer.get(seq);
            data.setSequencer(seq);
            data.setMessage(message);
        } finally {
            ringBuffer.publish(seq);
        }
    }

}
